<template>
  <el-drawer :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="80px"
      v-loading="formLoading"
    >
      <el-form-item label="支付类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择支付类型" disabled class="!w-240px">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PAY_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
        <el-text v-if="formData.code === 'wx_lite'" type="info">
          <a
            href="https://pay.weixin.qq.com/doc/v3/merchant/4013070756"
            target="_blank"
            class="ml-10px"
          >
            前往微信支付平台查看《开发必要参数说明》
          </a>
        </el-text>
      </el-form-item>
      <el-form-item label="支付渠道" prop="code">
        <el-select v-model="formData.code" placeholder="请选择支付渠道" disabled class="!w-240px">
          <el-option
            v-for="dict in getStrDictOptions(DICT_TYPE.PAY_CHANNEL_CODE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.code === 'wx_lite'" label="小程序Id" prop="wxApiV3AppId">
        <el-input v-model="wxConfig.appId" placeholder="请输入小程序AppId" />
      </el-form-item>
      <el-form-item v-if="formData.code === 'wx_lite'" label="商户号" prop="wxApiV3MchId">
        <el-input v-model="wxConfig.mchId" placeholder="请输入商户号" />
      </el-form-item>
      <el-form-item v-if="formData.code === 'wx_lite'" label="APIv3秘钥" prop="wxApiV3Key">
        <el-input v-model="wxConfig.secretKey" placeholder="请输入APIv3密钥" />
      </el-form-item>
      <el-form-item
        v-if="formData.code === 'wx_lite'"
        label="证书私钥"
        prop="wxApiV3PrivateKeyContent"
      >
        <el-input
          v-model="wxConfig.privateKeyContent"
          type="textarea"
          :rows="6"
          placeholder="请输入apiclient_key.pem内容"
        />
      </el-form-item>
      <el-form-item
        v-if="formData.code === 'wx_lite'"
        label="证书公钥"
        prop="wxApiV3PrivateCertContent"
      >
        <el-input
          v-model="wxConfig.privateCertContent"
          type="textarea"
          :rows="6"
          placeholder="请输入apiclient_cert.pem内容"
        />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" clearable />
      </el-form-item>
      <el-form-item label="开关" prop="enabled">
        <el-radio-group v-model="formData.enabled">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-drawer>
</template>
<script setup lang="ts">
import * as PayChannelApi from '@/api/pay/channel'
import { getTenantId } from '@/utils/auth'
import { DICT_TYPE, getStrDictOptions, getBoolDictOptions } from '@/utils/dict'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const tenantId = ref(getTenantId())

console.log('tenantId:', tenantId.value)

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<any>({
  id: undefined,
  type: undefined,
  code: undefined,
  config: undefined,
  enabled: undefined,
  sort: undefined
})
const wxConfig = ref<any>({
  appId: '',
  mchId: '',
  secretKey: '',
  privateKeyContent: '',
  privateCertContent: ''
})
const formRules = reactive({
  type: [{ required: true, message: '支付类型不能为空', trigger: 'change' }],
  code: [{ required: true, message: '支付渠道不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number | string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PayChannelApi.getPayChannel(id)
      if (formData.value.type === 'wechat') {
        wxConfig.value = JSON.parse(formData.value.config)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formData.value.type === 'wechat') {
      data.config = JSON.stringify(wxConfig.value)
    }
    if (formType.value === 'update') {
      await PayChannelApi.updatePayChannel(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    type: undefined,
    code: undefined,
    config: undefined,
    enabled: undefined,
    sort: undefined
  }
  formRef.value?.resetFields()
}
</script>
